const API = require('../../utils/api')
/**
 * 历城区政府 36.67373°N, 117.05027°E
 * 唐冶街道 36.66807°N, 117.24691°E
 * 鲍山街道 36.74038°N, 117.17868°E 
 */
Page({
  data: {
    banners: [
      {
        id: 1,
        image: 'https://picsum.photos/800/600?random=1',
        title: '专业网球场地',
        subtitle: '高品质场地，预约便捷',
        link: '/pages/courts/courts'
      },
      {
        id: 2,
        image: 'https://picsum.photos/800/600?random=1',
        title: '明星教练团队',
        subtitle: '一对一专业指导',
        link: '/pages/coaches/coaches'
      },
      {
        id: 3,
        image: 'https://picsum.photos/800/600?random=1',
        title: '精品教学视频',
        subtitle: '从零基础到进阶',
        link: '/pages/videos/videos'
      }
    ],
    nearbyCourts: [],
    userLocation: {
      longitude: 117.05027, // 历城区政府
      latitude: 36.67373,
    },
    markers: [],
    showNearbyList: false,
    searchValue: ''
  },
  async onLoad() {
    await this.getUserLocation();
    this.loadNearByLocationData();
  },
  
  onShow() {
  },

  // 获取用户位置
  async getUserLocation() {
    try {
      const res = await wx.getLocation({
        type: 'gcj02',
        altitude: true
      });
      this.setData({
        'userLocation.longitude': res.longitude,
        'userLocation.latitude': res.latitude
      });
    } catch (error) {
      console.log('获取位置失败，使用默认位置');
      // 使用默认位置
      this.loadNearByLocationData();
    }
  },

  // 根据位置获取数据并创建地图标记
  loadNearByLocationData(){
    let queryForm = {...this.data.userLocation,keyWords:this.data.searchValue};
    API.nearByLocationData(queryForm).then(res => {
      const courts = res || [];
      // 创建场地标记
      const courtMarkers = courts.map((court, index) => ({
        id: court.id,
        latitude: court.latitude,
        longitude: court.longitude,
        title: court.name,
        iconPath: '/images/courts.png',
        width: 30,
        height: 30,
        callout: {
          content: `${court.name}\n¥${court.price}/小时`,
          color: '#ffffff',
          fontSize: 12,
          borderRadius: 10,
          bgColor: '#1E90FF',
          padding: 5,
          display: 'ALWAYS'
        }
      }));
      
      // 添加用户位置标记（特殊标记）
      const userMarker = {
        id: 0, // 用户位置使用特殊ID
        latitude: this.data.userLocation.latitude,
        longitude: this.data.userLocation.longitude,
        title: '我的位置',
        iconPath: '/images/user.png',
        width: 40,
        height: 40,
        callout: {
          content: '我的位置',
          color: '#ffffff',
          fontSize: 12,
          borderRadius: 10,
          bgColor: '#ff4757',
          padding: 5,
          display: 'ALWAYS'
        }
      };
      // 合并标记，用户位置放在最后确保显示在最上层
      const allMarkers = [...courtMarkers, userMarker];
      // 计算包含所有标记点的区域
      const includePoints = [
        {
          latitude: this.data.userLocation.latitude,
          longitude: this.data.userLocation.longitude
        },
        ...courts.map(court => ({
          latitude: court.latitude,
          longitude: court.longitude
        }))
      ];
      
      this.setData({
        nearbyCourts: courts,
        markers: allMarkers,
        includePoints: includePoints
      });
    });
  },

  async loadFeaturedCoaches() {
    const res = await getApp().request({
      url: '/coaches/featured',
      data: { limit: 4 }
    })
    return res.data || []
  },

  async loadHotVideos() {
    const res = await getApp().request({
      url: '/videos/hot',
      data: { limit: 4 }
    })
    return res.data || []
  },

  async loadLatestMatches() {
    const res = await getApp().request({
      url: '/matches/latest',
      data: { limit: 3 }
    })
    return res.data || []
  },

  // 页面跳转
  goToCourts() {
    wx.navigateTo({
      url: '/pages/courts/courts'
    })
  },

  goToCoaches() {
    wx.navigateTo({
      url: '/pages/coaches/coaches'
    })
  },

  goToEvaluate() {
    wx.navigateTo({
      url: '/pages/evaluate/evaluate'
    })
  },

  toTeaching() {
    wx.navigateTo({
      url: '/pages/teaching/teaching'
    })
  },

  tournament() {
    wx.navigateTo({
      url: '/pages/tournament/tournament'
    })
  },

  goToCourtDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/court-detail/court-detail?id=${id}`
    })
  },

  goToCoachDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/coach-detail/coach-detail?id=${id}`
    })
  },

  goToVideoDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/video-detail/video-detail?id=${id}`
    })
  },

  goToMatchDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/matches/matches?id=${id}`
    })
  },

  // 地图相关方法
  moveToCurrentLocation() {
    this.mapCtx = wx.createMapContext('nearbyMap');
    this.mapCtx.moveToLocation();
  },

  onMarkerTap(e) {
    const markerId = e.markerId;
    // 用户位置标记ID为0，不跳转
    if (markerId === 0) {
      return;
    }
    const court = this.data.nearbyCourts.find(item => item.id === markerId);
    if (court) {
      wx.navigateTo({
        url: `/pages/court-detail/court-detail?id=${court.id}`
      });
    }
  },

  onCalloutTap(e) {
    const markerId = e.markerId;
    // 用户位置标记ID为0，不跳转
    if (markerId === 0) {
      return;
    }
    const court = this.data.nearbyCourts.find(item => item.id === markerId);
    if (court) {
      wx.navigateTo({
        url: `/pages/court-detail/court-detail?id=${court.id}`
      });
    }
  },

  toggleNearbyList() {
    this.setData({
      showNearbyList: !this.data.showNearbyList
    });
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '网事通 - 专业的网球服务平台',
      path: '/pages/index/index',
      imageUrl: '/images/share-banner.jpg'
    }
  },

  // 搜索功能 - 简单的输入监听
  onSearchInput(e) {
    const searchValue = e.detail.value;
    this.setData({ searchValue });
    // 这里可以添加自定义的监听逻辑
    console.log('搜索框内容改变:', searchValue);
    this.loadNearByLocationData(); 
  },

  // 搜索确认
  onSearchConfirm() {
    const { searchValue } = this.data;
    if (!searchValue.trim()) return;
    
    wx.navigateTo({
      url: `/pages/search/search?keyword=${encodeURIComponent(searchValue)}`
    });
  },
})
